<template>
  <div class="index-header">
    <ul class="list">
      <!-- <li class="item item-btn" @click="goPage">
        <div class="item-btn-button">进入大屏</div>
      </li> -->
      <li>
        <el-popover placement="top" width="400" trigger="click" @show="showNewNotify">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="我的站内信" value="0">
              <div class="msg-big">
                <el-table ref="multipleTable" :data="msglist" tooltip-effect="dark" style="width: 100%"
                  max-height="300">
                  <el-table-column show-overflow-tooltip prop="templateContent" label="内容">
                  </el-table-column>
                  <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" align="right">
                    <template slot-scope="scope">
                      <div>{{ formatterTime(scope.row.createTime) }}</div>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="msg-btn">
                  <el-button type="primary" @click="handlego">查看全部</el-button>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
          <el-badge :is-dot="readDrawer" class="badgeitem" slot="reference">
            <el-button plain icon="el-icon-bell"
              style="border: none; font-size: 18px; padding: 5px 5px 0 0"></el-button>
          </el-badge>
        </el-popover>
      </li>
      <li class="item">
        <el-dropdown @command="handleCommand">
          <div style="display: flex; align-items: center; color: white">
            <img v-if="$store.state.userInfo.headPic" class="item-user1" :src="$store.state.userInfo.headPic" alt="" />
            <img v-else src="~images/headPic.png" alt="" class="item-user1" />
            <p class="item-text">{{ $store.state.userInfo.username }}</p>
            <i class="iconfont iconxiala item-user"></i>
          </div>
          <el-dropdown-menu slot="dropdown">
            <!-- <el-dropdown-item command="msg">个人信息</el-dropdown-item> -->
            <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </li>
      <!-- <li class="item" @click="$emit('change-password')">
        <i class="iconfont icon4xiugaimima item-password"></i>
        <p class="item-text">修改密码</p>
      </li> -->
      <!-- <li class="item" @click="handleLogout">
        <i class="iconfont icontuichu item-logout"></i>
        <p class="item-text">退出</p>
      </li> -->
    </ul>
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="40%" append-to-body
      :before-close="handleClosePassword">
      <div>
        <el-input v-model="password" placeholder="请输入密码" show-password></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureChangePassword">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import API from "@/api/apiBase";
import APINotify from "@/api/apiNotify";
import { mapState, mapActions } from "vuex";

export default {
  name: "IndexHeader",
  data() {
    return {
      passwordDialogVisible: false,
      password: null,
      readDrawer: false,
      showMail: false,
      activeName: "0",
      msglist: [],
    };
  },
  methods: {
    sureChangePassword() {
      let params = {
        token: this.$store.state.token,
        password: this.password,
      };
      API.upLoginUserPassword(params).then((res) => {
        if (res.key === 1000) {
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          this.passwordDialogVisible = false;
          this.password = null;
        }
      });
    },
    handleClosePassword() {
      this.passwordDialogVisible = false;
    },
    goPage() {
      this.$router.push({
        path: "/homePage",
      });
    },
    handlego() {
      this.$router.push({
        path: "/MessageCenter",
      });
    },
    handleCommand(command) {
      if (command == "logout") {
        this.handleLogout();
      } else if (command == "msg") {
        this.$router.push({
          path: "/EditUser1",
          query: {
            type: 1,
          },
        });
      } else if (command == "changePassword") {
        // 修改密码
        this.password = null;
        this.passwordDialogVisible = true;
      }
    },
    handleLogout() {
      const params = {
        token: this.$store.state.token,
      };
      API.logout(params).then((res) => {
        if (res.key === 1000) {
          this.$ls.remove("mujingtoken");
          this.$ls.remove("mujinguserInfo");
          this.$ls.remove("mujingpermissionList");
          this.$ls.remove("mujingpermissionNameList");
          location.reload();
          // location.href = "/#/login";
          // this.$router.push({
          //   path: "/logout"
          // });
        }
      });
    },

    // notifyListfun() {
    //   let params = {
    //     pageNum: 1,
    //     pageSize: 5,
    //     readStatus: 0,
    //   };
    //   APINotify.notifyList(params).then((res) => {
    //     if (res.key == 1000) {
    //       this.msglist = res.result.list;
    //     }
    //   });
    // },

    handleClickOutside(event) {
      // 获取 .mail 元素
      const mailElement = document.querySelector(".mail");
      if (this.showMail && mailElement && !mailElement.contains(event.target)) {
        this.showMail = false;
      }
    },

    formatterTime(time) {
      return this.$moment(time).format("YYYY-MM-DD HH:mm:ss");
    },

    handleClick(tab, event) {
      console.log(tab, event);
    },

    getIsRead() {
      let params = {
        pageNum: 1,
        pageSize: 1,
        readStatus: 0,
      };
      APINotify.notifyList(params).then((res) => {
        if ((res.key = 1000)) {
          if (res.result.list.length > 0) {
            this.readDrawer = true;
          } else {
            this.readDrawer = false;
          }
          this.handleChangeisRead(this.readDrawer);
        }
      });
    },

    showNewNotify(){
      //this.notifyListfun()
    },

    ...mapActions(["handleChangeisRead"]),
  },
  watch: {
    // 监听 Vuex 的 isRead 状态变化
    // "$store.state.isRead"(newVal, oldVal) {
    //   console.log("isRead changed:", newVal, oldVal);
    //   this.readDrawer = newVal; // 同步更新 readDrawer
    //   if(newVal){
    //     this.getIsRead()
    //   }
    // },
    "$store.state.hasNewNotify": {
      handler(newVal, oldVal) {
        console.log("hasNewNotify 变化：", newVal, oldVal);
        this.readDrawer = newVal;
        if (newVal) {
          this.getIsRead();
        }
      },
      immediate: true, // 初始化时立即执行一次
      deep: false // 这里不需要 deep，因为 isRead 是基本类型
    },
  },

  created() {
   // this.getIsRead();
  },

  mounted() {
    //this.notifyListfun();
    // 添加全局点击事件监听器
    document.body.addEventListener("click", this.handleClickOutside);
    // this.$bus.$on('websocket-message', this.handleNewMessage);
  },

  beforeDestroy() {
    document.body.removeEventListener("click", this.handleClickOutside);
  },
};
</script>

<style>
.overflow-y-box {
  overflow-y: auto;
}

.overflow-y-box::-webkit-scrollbar {
  display: none;
}
.msgbox {
  margin: 10px 0;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #dcdfe6;
}
.msgbox:nth-child(1) {
  margin: 0 0 10px 0;
}

.msg-big {
  position: relative;
  height: 400px;
}

.msg-btn {
  position: absolute;
  right: 1%;
  bottom: 2%;
}
</style>

<style lang="sass" scoped>
.index-header
  height: 65px
  position: fixed
  top: 0
  left: 180px
  right: 0
  background: #ffffff
  color: #45546C
  padding-left: 30px
  padding-right: 65px
  display: flex
  justify-content: flex-end
  align-items: center
  z-index: 2000
  .list
    display: flex
    align-items: center
    .item
      margin:0 50px 0 30px
      display: flex
      align-items: center
      cursor: pointer
      &.item-btn
        width: 98px
        height: 28px
        display: flex
        align-items: center
        justify-content: center
        background: url(~images/header_btn_icon.png) center/cover no-repeat
        .item-btn-button
          width: 84px
          height: 36px
          background: #03C192
          border-radius: 4px
          font-size: 14px
          color: #FFFFFF
          line-height: 36px
          text-align: center
        .item-dashboard
          color: #45546C
      &:last-child
        margin-right: 0
      .item-text
        margin-left: 8px
        color: #45546C!important
      .item-user
        font-size: 20px
        color: #45546C
      .item-user1
        width: 36px
        height: 36px
      .item-password
        font-size: 14px
      .item-logout
        font-size: 14px
</style>
